var data1 = [{'id':'1','customerstype':'text1','customerstname':'text2','cucustomerscode':'text3','referred':'text4','countries':'text5','customerlevel':'text6','customersource':'text7','businesstypes':'text8','url':'text9','subordinatesalesman':'text10'}];

var layer = layui.layer //弹层
    ,table = layui.table //表格
    form = layui.form,$ = layui.jquery, element = layui.element
     ,flag=getQueryVariable("flag")//flag=kh:表示客户；flag=gys：表示供应商
        ,type=getQueryVariable("type")
      ,distributionid="",lxrname="",lxremail="",processid=""
    ;
//当前登录人所管理的员工
var manageRuls=JSON.parse(window.sessionStorage.getItem("manageRuls"));//getManageRule("supplierSalesman");
var userTree=JSON.parse(window.sessionStorage.getItem("userTree"));
var sharecustomer = [];//共享客户id列表


//从字典中获取信息
var djs=JSON.parse(window.sessionStorage.getItem("djs"));//=getdictionaryF(6,26);//客户等级
var gysdj=JSON.parse(window.sessionStorage.getItem("gysdj"));//=getdictionaryF(6,35);//供应商等级
//var fls=JSON.parse(window.sessionStorage.getItem("fls"));//=getdictionary(6,27);//客户类型
var countrys=JSON.parse(window.sessionStorage.getItem("countrys"));//=getdictionaryF(6,29);//国家/地区
var sourceOfCustomerss=JSON.parse(window.sessionStorage.getItem("sourceOfCustomerss"));//=getdictionaryF(1,3);//客户来源
var businessTypes=JSON.parse(window.sessionStorage.getItem("businessTypes"));//=getdictionaryF(6,33);//业务类型
var spstatuss=JSON.parse(window.sessionStorage.getItem("spstatuss"));//=getdictionaryF(6,34);//审批状态
var fls=JSON.parse(window.sessionStorage.getItem("gysfl"));//供应商分类
var soc=JSON.parse(window.sessionStorage.getItem("sourceOfCustomers"));//付款类型
//var salemans=manageRuls;
let salesmanCodes="";//所属 业务员下拉框选择值

let share22="";
let shareopenwind;
//var salemans=querysalemans();//获以所有业务员的编码、名称
var salemans=manageRuls;
//判断是否是客户还是供应商
/*if(flag=="gys"){
    $("#khpool").css("display","none");
    $("#khpooldiv").css("display","none");
    $("button#addpubpool.layui-btn.layui-btn-sm").css("display","none")
}*/
//客户类型查询条件赋值
//setType();
if(type==""){
    for(var i=0;i<fls.length;i++){
        type=type+","+fls[i].code;
    }
}
let isMsn="否";//财务部管理员
let isisFinances=false;//财务部人员

isMsnF();
function isMsnF() {
    $.ajax({
        url: 'customer2/isMsn',
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            isMsn=date.data
        }
    })
}
isFinance();
function isFinance() {
    $.ajax({
        url: 'customer2/isFinance',
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            isisFinances=date.data
        }
    })
}
if (!isisFinances){
    document.getElementById("delet").style.display = "none";
}


initable22();
initable33();
//---客户查询
table.render({
    elem: '#customerselect'
    //,data:data1
    , type: 'get'
    , url: 'customer2/selectByPage'
    ,where:{
        "type":type,
        "name":"",
        "saleman":user.customerRole,
        "flag":flag
    }
    , toolbar: true
    , cols: [[
        {checkbox: true}
        , {field: 'type', title: '类型', width: 150}
        , {field: 'name', title: '名称', event: "customerstname", width: 350}
        , {field: 'code', title: '供应商编码', event: "cucustomerscode", width: 150}
        , {field: 'abbreviation', title: '简称', event: "referred", width: 120}
        , {field: 'paymentAccountNo', title: '供应商代码', width: 120}
        , {field: 'country', title: '国家', width: 120}
        , {field: 'level', title: '等级', width: 120}
        , {field: 'businessType', title: '业务类型', width: 120}
        , {field: 'homepage', title: '网址', width: 200}
        , {field: 'salesman', title: '所属业务员', width: 120}
        // , {field: 'spstatus', title: '审批状态'}
        , {field: 'sourceOfCustomers', title: '付款类型', width: 200}
        , {field: 'tempStatus', title: '审批状态', width: 120}
        , {fixed: 'right', width: 350, align: 'center', toolbar: '#customerup', title: '操作'}
    ]]
    , id: 'customertableid'
    , height: $(document).height() - $('#customerselect').offset().top - 50
    , page: true
    , limit: 50
    , limits: [50,100,200,300,500,1000]
    , done: function (res, curr, count) {
        //客户类型
         getselectText(fls,"type");
        //国家
        getselectText(countrys,"country");
        //客户等级
        // getselectText(djs,"level");
        //供应商等级
        getselectText(gysdj,"level");
        // //客户来源
        // getselectText(sourceOfCustomerss,"sourceOfCustomers");
        //业务类型
        getselectText(businessTypes,"businessType");
        //审批状态
        getselectText(spstatuss,"spstatus");
       // initable22();
        //付款类型
        getselectText(soc,"sourceOfCustomers");
    }
});



form.render();


function getselectText( dt,key){
    $("[data-field = '"+key+"']").children().each(function(){
        for(var i=0;i<dt.length;i++){
            if($(this).text() == dt[i].code){
                $(this).text(dt[i].name);
            }
        }
    })
}
//查询条件
table.on('toolbar(customertable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    var data = checkStatus.data;
    var cucustomers = $('#cucustomers').val();//客户名称
    var cucustomerstype = $("input[name='cucustomerstype2']")[0].value;//客户类型
    if(cucustomerstype==""){
        for(var i=0;i<fls.length;i++){
            cucustomerstype=cucustomerstype+","+fls[i].code;
        }
    }
    if(salesmanCodes.options != undefined){
        salesmanCodes=user.code;
    }
    var saleman=salesmanCodes;//$('#salesman option:selected').val();//所属业务员
    switch(obj.event){
        case 'shared':
            if(data.length ==0){
                layer.msg("请选择要共享的供应商");
                break;
            }
           /* for(var i=0;i<data.length;i++){
                if(data[i].processid ==null){
                    layer.msg("选择的数据未审批，不能进行共享");
                    return;
                }
            }*/

            for (var i = 0;i<data.length;i++){
                sharecustomer.push(data[i].code)
            }
            layer.open({
                type: 1,
                title: "共享供应商",
                area: ['300px', '200px'],
                content: $("#shared")//引用的弹出层的页面层的方式加载修改界面表单
            });
            break;
        case 'new'://新增
            parent.intab("views/jsp/BasicData/tpl/customer2info.jsp","添加供应商信息")
            break;
        case 'delet'://删除
            var delid = [];
            for (var i = 0;i<data.length;i++){
                if(data[i].processid !=null){
                    layer.msg("选择的数据已发起审批，不能进行删除");
                    return;
                }
                delid.push(data[i].id)
            }
            if(delid.length==0){
                layer.msg("请选择要删除的数据");
                break;
            }
            if(delCustomer(delid)){
                layer.msg("删除成功");
                table.reload('customertableid', {
                    type: 'get'
                    , url: 'customer2/selectByPage'
                    ,   page: {
                        curr: 1, //重新从第 1 页开始
                        limit: 50
                    }
                    ,where:{
                        "type":cucustomerstype,
                        "name":cucustomers,
                        "saleman":saleman
                    }

                }, 'data');
                getxmselect2("#cucustomerstype2","cucustomerstype2", getxmlselectfls(fls));
            }else{
                layer.msg("删除失败");
            }
           // layer.msg('需要删除的数据ID为：'+ JSON.stringify(delid) + ',执行删除');

            break;
        case 'searchs':

           // var salesman = $('#salesman option:selected').val();//所属业务员
           // layer.msg("搜索"+cucustomers+","+cucustomerstype+","+salesman);
            //执行重载
            table.reload('customertableid', {
                type: 'get'
               , url: 'customer2/selectByPage'
               ,page: {
                    curr: 1 //重新从第 1 页开始
                }
                ,where:{
                    "type":cucustomerstype,
                    "name":cucustomers,
                    "saleman":saleman
                }

            }, 'data');
            //类型

            getxmselect2("#cucustomerstype2","cucustomerstype2", getxmlselectfls(fls));
            initable22();

            form.render();


            break;
        case 'publicpool':
            if(data.length==0){
                layer.msg('请选择加入公共池的客户')
            }else{
                var delid = [];
                for (var i = 0;i<data.length;i++){
                    if(data[i].processid ==null){
                        layer.msg("选择的数据未审批，不能加入公共池");
                        return;
                    }
                    delid.push(data[i].id)
                }
                if(addpublicPool(delid)){
                    layer.msg("加入公共池成功");

                    //执行重载
                    table.reload('customertableid', {
                        type: 'get'
                        , url: 'customer2/selectByPage'
                        ,page: {
                            curr: 1 //重新从第 1 页开始
                        }
                        ,where:{
                            "type":cucustomerstype,
                            "name":cucustomers,
                            "saleman":saleman
                        }

                    }, 'data');

                }else{
                    layer.msg("加入公共池失败");
                }
               // layer.msg('需要加入公共池的数据ID为：'+ JSON.stringify(delid));
            }
            break;
    };
});
//修改、查看
table.on('tool(customertable)', function(obj){
    var data = obj.data;
    if(obj.event === 'customerup') {
        parent.intab("views/jsp/BasicData/tpl/customer2info.jsp?id="+obj.data.id,"修改供应商信息")
        window.sessionStorage.setItem("processid",data.processid);
    }else if(obj.event === 'customerstname' || obj.event === 'cucustomerscode' || obj.event === 'referred') {
        parent.intab("views/jsp/BasicData/tpl/viewcustomer2info.jsp?id="+obj.data.id,"供应商信息")
    }else if(obj.event === 'addB'){

        var param={};
        param.status="B";
        param.id=obj.data.id;
        if(update(param)){
            layer.msg("添加黑名单成功!");
            refash();
        }else{
            layer.msg("添加黑名单失败!");
        }
        //调用更新方法更新状态
    }else if(obj.event === 'cacleB'){
        //调用更新方法更新状态
        var param={};
        param.status="";
        param.id=obj.data.id;
        if(update(param)){
            layer.msg("取消黑名单成功!");
            refash();
        }else{
            layer.msg("取消黑名单失败!");
        }
    }else if(obj.event === 'submits'){
        //调用更新方法更新状态
        var param={};
        param.tempStatus=2;
        param.id=obj.data.id;
        if(update(param)){
            layer.msg("提交审批成功!");
            refash();
        }else{
            layer.msg("提交审批失败!");
        }
    }else if(obj.event === 'through'){
        //调用更新方法更新状态
        var param={};
        param.tempStatus=3;
        param.id=obj.data.id;
        if(update(param)){
            layer.msg("审批通过成功!");
            refash();
        }else{
            layer.msg("审批通过失败!");
        }
    }else if(obj.event === 'backtothe'){
        //调用更新方法更新状态
        var param={};
        param.tempStatus=1;
        param.id=obj.data.id;
        if(update(param)){
            layer.msg("审批退回成功!");
            refash();
        }else{
            layer.msg("审批退回失败!");
        }
    }
});

function update(data){
    var tf=false;
    $.ajax({
        type : 'get',
        //  url : 'resource/getTree',
        data:{"id":data.id,"status":data.status,"tempStatus":data.tempStatus},
        url:'customer2/updateHByKey',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}

//---联系人查询
table.render({
    elem: '#contactselect'
    ,type:"get"
    ,url:"customer2contact/select2ByPage"
    ,where:{
        "company":"",
        "name":"",
        "email":""
    }
    ,toolbar: '#contactquerytoolbar'
    ,cols: [[
        {checkbox: true, fixed: true}
        ,{field:'companyname', title:'公司名称', sort: true, event: "companyaffiliation"}
        ,{field:'name', title:'联系人名称', sort: true}
        ,{field:'email', title:'邮箱地址', sort: true}
        ,{field:'post', title:'职务', sort: true}
        ,{field:'tel', title:'电话', sort: true}
        ,{field:'phone', title:'手机', sort: true}
        ,{field:'wx', title:'微信', sort: true}
        ,{field:'expressAddress', title:'快件地址', sort: true}
        ,{field:'birthday', title:'联系人生日', sort: true}
        ,{field:'remark', title:'联系人备注', sort: true}
        // ,{field:'salesman', title:'业务员', sort: true}
        //,{fixed: 'right', width:150, align:'center', toolbar: '#customerup', title:'操作'}
    ]]
    ,id: 'contacttableid'
    ,height: $(document).height() - $('#contactselect').offset().top - 50
    ,page: true
});
//详情，双击
table.on('tool(contacttable)', function(obj){
    var data = obj.data;
    //根据供应商编码获取供应商id
    var id= getIdBycode(data.company);
    data.id=id;

    if(obj.event === 'companyaffiliation' || obj.event === 'contactname') {
        parent.intab("views/jsp/BasicData/tpl/viewcustomer2info.jsp?id="+obj.data.id,"供应商信息")
    }
});
//联系人查询条件
table.on('toolbar(contacttable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
        case 'searchs':
            var contactinfo = $('#contactinfo').val();
            var contactemail = $('#contactemail').val();
           // layer.msg("搜索"+contactinfo+","+contactemail);
            //执行重载
            table.reload('contacttableid', {
                type:"get"
                ,url:"customer2contact/select2ByPage"
                ,where:{
                "company":"",
                "name":contactinfo,
                "email":contactemail
               },
                page: {
                    curr: 1 //重新从第 1 页开始
                }

            }, 'data');
            break;
    };
});

//---公共客户池
table.render({
    elem: '#customerpoolselect'
    , type: 'get'
    , url: 'customer2/select3ByPage'
    ,where:{
        "name":"",
        "type":""
    }
    , toolbar: '#commonclienttoolbar'
    , cols: [[
        {checkbox: true, fixed: true}
        , {field: 'type', title: '客户类型', fixed: true}
        , {field: 'name', title: '客户名称', fixed: true, event: "customerstname"}
        , {field: 'code', title: '客户代码', fixed: true, event: "cucustomerscode"}
        , {field: 'abbreviation', title: '简称', fixed: true, event: "referred"}
        , {field: 'country', title: '国家', fixed: true}
        , {field: 'level', title: '客户等级', fixed: true}
        , {field: 'sourceOfCustomers', title: '客户来源', fixed: true}
        , {field: 'businessType', title: '业务类型', fixed: true}
        , {field: 'homepage', title: '网址', fixed: true}

    ]]
    ,id: 'customerpooltableid'
    ,height:  $(document).height() - $('#customerpoolselect').offset().top - 50
    ,page: true
    , done: function (res, curr, count) {
        //客户类型
        getselectText(fls,"type");
        //国家
        getselectText(countrys,"country");
        //客户等级
        getselectText(djs,"level");
        //客户来源
        getselectText(sourceOfCustomerss,"sourceOfCustomers");
        //业务类型
        getselectText(businessTypes,"businessType");
        //审批状态
        getselectText(spstatuss,"spstatus");
    }
});
table.on('tool(customerpooltable)', function(obj){
    var data = obj.data;
    if(obj.event === 'customerstname' || obj.event === 'cucustomerscode' || obj.event === 'referred') {
        parent.intab("views/jsp/BasicData/tpl/viewcustomer2info.jsp?id="+obj.data.id,"供应商信息")
    }
});
//公共池
table.on('toolbar(customerpooltable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    var data = checkStatus.data;
    var cocustomersinfo = $('#cocustomersinfo').val();
    var cocustomerstype = $('#cocustomerstype2 option:selected').val();
    switch(obj.event){
        case 'dicustomers':
            if(data.length==0){
                layer.msg('请选择需要分配客户')
            }else{
                var delid = [];
                for (var i = 0;i<data.length;i++){
                    delid.push(data[i].id)
                }
                distributionid = delid;
                layer.open({
                    type: 1,
                    title: "分配客户",
                    area: ['300px', '200px'],
                    content: $("#dicustomers")//引用的弹出层的页面层的方式加载修改界面表单
                });

                //ajax得到业务员列表 给select赋值
                $("#customersalesman").html("");
                var customerdata = getusers();//[{name:"text1",value:"text1"},{name:"text2",value:"text2"}];

                for(var i =0;i<customerdata.length;i++){
                    $("#customersalesman").append("<option value=\""+customerdata[i].code+"\">"+customerdata[i].name+"</option>");
                }
                form.render('select');

                //layer.msg('需要设为自己的客户的数据ID为：'+ JSON.stringify(distributionid));
            }
            break
        case 'searchs'://搜索

           // layer.msg("搜索"+cocustomersinfo+","+cocustomerstype);
            //执行重载
            table.reload('customerpooltableid', {
                type: 'get'
                , url: 'customer2/select3ByPage'
                ,where:{
                    "name":cocustomersinfo,
                    "type":cocustomerstype
                },
                page: {
                    curr: 1 //重新从第 1 页开始
                }

            }, 'data');
            break;
        case 'setcustomer'://设为自己
            if(data.length==0){
                layer.msg('请选择设为自己的客户')
            }else{
                var delid = [];
                for (var i = 0;i<data.length;i++){
                    delid.push(data[i].id)
                }
                if(setself(delid)){
                    layer.msg("设置成功");
                    //执行重载
                    table.reload('customerpooltableid', {
                        type: 'get'
                        , url: 'customer2/select3ByPage'
                        ,where:{
                            "name":cocustomersinfo,
                            "type":cocustomerstype
                        },
                        page: {
                            curr: 1 //重新从第 1 页开始
                        }

                    }, 'data');
                }else{
                    layer.msg("设置失败");
                }
               // layer.msg('需要设为自己的客户的数据ID为：'+ JSON.stringify(delid));
            }
            break;
    };
});
//监听提交,分配客户
form.on('submit(dicustomerssubmit)', function(data){
    var cocustomersinfo = $('#cocustomersinfo').val();
    var cocustomerstype = $('#cocustomerstype option:selected').val();
    if(savefp(data)){
        layer.msg("分配客户成功", {icon: 6});
        //执行重载
        table.reload('customerpooltableid', {
            type: 'get'
            , url: 'customer2/select3ByPage'
            ,where:{
                "name":cocustomersinfo,
                "type":cocustomerstype
            },
            page: {
                curr: 1 //重新从第 1 页开始
            }

        }, 'data');
    }else {
        layer.msg("分配客户失败", {icon: 6});
    }

    layer.closeAll();
    //data.field 为表单数据 distributionid为需要分配的客户ID

    return false;
});
/*$("#customerstatistics").on("click",function () {
    parent.intab("views/jsp/WarehouseManagement/tpl/statistics.jsp","客户统计");
})
$("#commonsettings").on("click",function () {
    parent.intab("views/jsp/BasicData/tpl/commonsettings.jsp","公共池设置");
})*/

/*layui.use(['dropdown'], function () {
    let dropdown = layui.dropdown;
    dropdown.onFilter("customer2statistics", function (event) {
        parent.intab("views/jsp/report/reportSuplier.jsp?ym=customerSuplier","供应商帐期详情");
       /!* switch (event) {
            case "s1":
                parent.intab("views/jsp/report/reportSuplier.jsp?ym=customerSuplier")
                break
            case "s2":
                parent.intab("views/jsp/report/reportCustomerShare.jsp?ym=customerShare")
                break
            case "s3":
                parent.intab("views/jsp/report/reportCount.jsp?ym=customerCount")
                break
        }*!/
    });
})*/
layui.use(['dropdown'], function () {
    let dropdown = layui.dropdown;
    dropdown.onFilter("customer2statistics", function (event) {
        switch (event) {
            case "s1":
                parent.intab("views/jsp/report/reportSuplier.jsp?ym=customerSuplier")
                break
            case "s2":
                parent.intab("views/jsp/report/supAccDeColl.jsp","供应商账期详情");
                break
            case "s3":
                parent.intab("views/jsp/report/supAmountAndPurAmount.jsp","供应商采购金额及出货金额统计");
                break
        }
    });
})


//监听提交,共享客户
form.on('submit(sharesubmit)', function(data){
    // var cocustomersinfo = $('#cocustomersinfo').val();
    // var usercode = $('#share option:selected').val();
    var usercode=data.field.share;
    if(saveshare(usercode)){
        layer.msg("共享供应商成功", {icon: 6});
        setTimeout(function(){
            initable33();
            layer.closeAll();
        },2000);
    }else {
        layer.msg("共享供应商失败", {icon: 6});
    }


    //data.field 为表单数据 distributionid为需要分配的客户ID

    return false;
});
//批量删除
function delCustomer(ids) {
    var tf=false;
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data:{"ids":JSON.stringify(ids)},
        url:'customer2/delete',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}
function  setType() {
   var options="<option value=''></option>";
    for(var i=0;i<fls.length;i++){
        options+="<option value='"+fls[i].code+"'>"+fls[i].name+"</option>";
    }
    /*$("input[name='cucustomerstype1']").append(options);
    $("input[name='cucustomerstype2']").append(options);*/
    $('#cucustomerstype2 option:selected').val()
    form.render('select');
}
//加入公共池
function addpublicPool(ids) {
    var tf=false;
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data:{"ids":JSON.stringify(ids)},
        url:'customer2/update',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}
//设为自己
function  setself(ids) {
    var tf=false;
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data:{"ids":JSON.stringify(ids)},
        url:'customer2/setself',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}
function getusers() {
    var tf=[];
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        //data:{"ids":JSON.stringify(ids)},
        url:'customer2/getusers',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}
//分配客户
function  savefp(data) {
    /*distributionid[0]//
    data.field.customersalesman;*/
    var tf=false;
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data:{"ids":JSON.stringify(distributionid),"saleman":data.field.customersalesman},
        url:'customer2/savefp',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;

}
function  querysalemans() {
    var sms=[];
    var objs= getusers();
    for(var i=0;i<objs.length;i++){
        var obj={};
        obj.code=objs[i].code;
        obj.name=objs[i].name;
        sms.push(obj);
    }
    return sms;
}
//判断是否是管理员
function  isGLY() {
    var tf=false;
    $.ajax({
        type : 'get',
        //  url : 'resource/getTree',
        //data:{"ids":JSON.stringify(ids)},
        url:'customer2/isGLY',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}
function  getIdBycode(code) {
    var tf=0;
    $.ajax({
        type : 'get',
        //  url : 'resource/getTree',
        data:{"code":JSON.stringify(code)},
        url:'customer2/getIdBycode',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}
function  saveshare(usercode) {
    var tf=false;
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data:{"usercode":JSON.stringify(usercode),"codes":JSON.stringify(sharecustomer)},
        url:'customer2/saveshare',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}

function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}
function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            //return this
            salesmanCodes="";
            for(var i=0;i<change.length;i++){
                if(i == change.length-1){
                    salesmanCodes=salesmanCodes+ change[i].value;
                }else{
                    salesmanCodes=salesmanCodes+ change[i].value+",";
                }
            }

        }
    })
}
function getxmselect222(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            //return this
            share22="";
            for(var i=0;i<change.length;i++){
                if(i == change.length-1){
                    share22=share22+ change[i].value;
                }else{
                    share22=share22+ change[i].value+",";
                }
            }

        }
    })
}



function initable22() {
//select over

//获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();

//let userTree = getAllJson(treeList.list);
//salesmanCodes= getxmselect("#salesman","subordinatesalesman", userTree);
//salesmanCodes= getxmselect("#salesman","subordinatesalesman", [{name: user.name, value: user.code}]);
    if(treeList && treeList.list){
        let userTree = getAllJson(treeList.list);
        //getxmselect("#operationCode","owneroperator", userTree);
        salesmanCodes= getxmselect("#salesman","subordinatesalesman", userTree);
    }else {
        //  getxmselect("#operationCode","owneroperator", [{name: user.name, value: user.code}]);
        salesmanCodes= getxmselect("#salesman","subordinatesalesman", [{name: user.name, value: user.code}]);
    }

}


function getxmlselectfls(){
    tmparr=[]
    for(let item of fls){
        tmparr.push({value:item.code,name:item.name})
    }
    return tmparr
}
getxmselect2("#cucustomerstype2","cucustomerstype2", getxmlselectfls(fls));
function getxmselect2(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {

        }
    })
}


function refash() {
    var cucustomers = $('#cucustomers').val();//客户名称
    var cucustomerstype = $("input[name='cucustomerstype2']")[0].value;//$('#cucustomerstype1 option:selected').val();//客户类型
    if(cucustomerstype==""){
        for(var i=0;i<fls.length;i++){
            cucustomerstype=cucustomerstype+","+fls[i].code;
        }
    }
    if(cucustomerstype==""){
        for(var i=0;i<fls.length;i++){
            cucustomerstype=cucustomerstype+","+fls[i].code;
        }
    }
    if(salesmanCodes.options != undefined){
        salesmanCodes=user.code;
    }
    var saleman=salesmanCodes;//$('#salesman option:selected').val();//所属业务员
    if(saleman==undefined)saleman="";
    //执行重载
    table.reload('customertableid', {
        type: 'get'
        , url: 'customer2/selectByPage'
        ,page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where:{
            "type":cucustomerstype,
            "name":cucustomers,
            "saleman":saleman
        }

    }, 'data');



  //  getxmselect2("#cucustomerstype2","cucustomerstype2", getxmlselectfls(fls));
    //类型

    getxmselect2("#cucustomerstype2","cucustomerstype2", getxmlselectfls(fls));
    initable22();
   // setselecttype(salemans,"share");
    //getxmselect2("#cucustomerstype2","cucustomerstype2", getxmlselectfls(fls));
}

//主页查询
$("#sharedZhu").on("click",function(){
    //共享
    var obj={};
    obj.event="shared";
    executeSearch(obj);
});
$("#print").on("click",function(){
    //共享
    var obj={};
    obj.event="print";
    executeSearch(obj);
});
$("#new").on("click",function(){
    //新增
    var obj={};
    obj.event="new";
    executeSearch(obj);
});
$("#delet").on("click",function(){
    //删除
    var obj={};
    obj.event="delet";
    executeSearch(obj);
});
$("#searchs").on("click",function(){
    // 搜索
    var obj={};
    obj.event="searchs";
    executeSearch(obj);
});
$("#addpubpool").on("click",function(){
    //加入公共池
    var obj={};
    obj.event="publicpool";
    executeSearch(obj);
});
$("#setUpSupplier").on("click",function(){
    layer.open({
        title:'设置',
        type: 2,
        area: ['800px', '400px'],
        content: 'views/jsp/BasicData/tpl/setUpSupplier.jsp'
    });
});
$("#uploadFile").on("click",function(){
    //上传文件
    let obj={};
    obj.event="uploadFile";
    executeSearch(obj);
});
function  executeSearch(obj) {
    var checkStatus = table.checkStatus("customertableid");
    var data = checkStatus.data;
    var cucustomers = $('#cucustomers').val();//客户名称
    var cucustomerstype = $("input[name='cucustomerstype2']")[0].value;//客户类型
    if(cucustomerstype==""){
        for(var i=0;i<fls.length;i++){
            cucustomerstype=cucustomerstype+","+fls[i].code;
        }
    }
    if(salesmanCodes.options != undefined){
        salesmanCodes=user.customerRole;
    }
    var saleman=salesmanCodes;//$('#salesman option:selected').val();//所属业务员
    switch(obj.event){
        case 'shared':
            if(data.length ==0){
                layer.msg("请选择要共享的供应商");
                break;
            }
            /*for(var i=0;i<data.length;i++){
                if(data[i].processid ==null){
                    layer.msg("选择的数据未审批，不能进行共享");
                    return;
                }
            }*/

            for (var i = 0;i<data.length;i++){
                sharecustomer.push(data[i].code)
            }
            initable33();
            shareopenwind=layer.open({
                type: 1,
                title: "共享供应商",
                area: ['500px', '300px'],
                content: $("#shared")//引用的弹出层的页面层的方式加载修改界面表单
            });
            break;
        case 'print':
            if(checkStatus.data.length > 1){
                layer.msg( "每次只能打印一个单据! ");
                break;
            }
            if(checkStatus.data.length == 0){
                layer.msg("请选择要打印的单据! ");
                break;
            }
            window.open("views/jsp/report.jsp?ym=suplier&code=code:"+checkStatus.data[0].code);
            break;

        case 'new'://新增
            parent.intab("views/jsp/BasicData/tpl/customer2info.jsp","添加供应商信息")
            break;
        case 'delet'://删除
            var delid = [];
            for (var i = 0;i<data.length;i++){
                if(data[i].processid !=null){
                    layer.msg("选择的数据已发起审批，不能进行删除");
                    return;
                }
                delid.push(data[i].id)
            }
            if(delid.length==0){
                layer.msg("请选择要删除的数据");
                break;
            }
            if(delCustomer(delid)){
                layer.msg("删除成功");
                table.reload('customertableid', {
                    type: 'get'
                    , url: 'customer2/selectByPage'
                    ,   page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where:{
                        "type":cucustomerstype,
                        "name":cucustomers,
                        "saleman":saleman
                    }

                }, 'data');
              //  getxmselect2("#cucustomerstype2","cucustomerstype2", getxmlselectfls(fls));
            }else{
                layer.msg("删除失败");
            }
            // layer.msg('需要删除的数据ID为：'+ JSON.stringify(delid) + ',执行删除');

            break;
        case 'searchs':

            // var salesman = $('#salesman option:selected').val();//所属业务员
            // layer.msg("搜索"+cucustomers+","+cucustomerstype+","+salesman);
            //执行重载
            table.reload('customertableid', {
                type: 'get'
                , url: 'customer2/selectByPage'
                ,page: {
                    curr: 1 //重新从第 1 页开始
                }
                ,where:{
                    "type":cucustomerstype,
                    "name":cucustomers,
                    "saleman":saleman
                }

            }, 'data');
            //类型

           // getxmselect2("#cucustomerstype2","cucustomerstype2", getxmlselectfls(fls));
            //initable22();

            form.render();


            break;
        case 'publicpool':
            if(data.length==0){
                layer.msg('请选择加入公共池的客户')
            }else{
                var delid = [];
                for (var i = 0;i<data.length;i++){
                    if(data[i].processid ==null){
                        layer.msg("选择的数据未审批，不能加入公共池");
                        return;
                    }
                    delid.push(data[i].id)
                }
                if(addpublicPool(delid)){
                    layer.msg("加入公共池成功");

                    //执行重载
                    table.reload('customertableid', {
                        type: 'get'
                        , url: 'customer2/selectByPage'
                        ,page: {
                            curr: 1 //重新从第 1 页开始
                        }
                        ,where:{
                            "type":cucustomerstype,
                            "name":cucustomers,
                            "saleman":saleman
                        }

                    }, 'data');

                }else{
                    layer.msg("加入公共池失败");
                }
                // layer.msg('需要加入公共池的数据ID为：'+ JSON.stringify(delid));
            }
            break;
        case 'uploadFile':
            parent.intab("views/jsp/BasicData/fileUpload.jsp?model=supplier","文件上传")
            break;
    };
}

function initable33() {
//获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();
    if(treeList && treeList.list){
        let userTree = getAllJson(treeList.list);
        share22= getxmselect222("#share","share", userTree);
    }else {
        share22= getxmselect222("#share","share", [{name: user.name, value: user.code}]);
    }

}